Page({
  data: {
    initQuestionsDone: false,
    initPapersDone: false,
    debugInfo: []
  },

  onLoad() {
    // 页面加载时检查集合是否存在
    this.checkCollections();
  },

  // 添加日志
  addLog(message) {
    console.log(message);
    const logs = this.data.debugInfo;
    logs.push(message);
    this.setData({
      debugInfo: logs
    });
  },

  // 检查集合是否存在
  async checkCollections() {
    try {
      const db = wx.cloud.database();
      
      this.addLog('开始检查集合...');
      
      // 检查questions集合
      try {
        const qCount = await db.collection('questions').count();
        this.addLog(`questions集合存在，共有${qCount.total}条数据`);
        this.setData({ initQuestionsDone: qCount.total > 0 });
      } catch (error) {
        this.addLog(`检查questions集合出错: ${error.message}`);
      }
      
      // 检查papers集合
      try {
        const pCount = await db.collection('papers').count();
        this.addLog(`papers集合存在，共有${pCount.total}条数据`);
        this.setData({ initPapersDone: pCount.total > 0 });
      } catch (error) {
        this.addLog(`检查papers集合出错: ${error.message}`);
      }
    } catch (error) {
      this.addLog(`数据库连接失败: ${error.message}`);
      wx.showToast({
        title: '数据库连接失败',
        icon: 'none'
      });
    }
  },

  // 初始化试题数据
  async initQuestions() {
    wx.showLoading({
      title: '初始化中...',
      mask: true
    });
    
    try {
      const db = wx.cloud.database();
      
      this.addLog('开始初始化试题数据...');
      
      // 示例试题数据
      const questions = [
        {
          title: '下列词语中加点字的读音完全正确的一项是',
          type: '单选题',
          subject: '语文',
          difficulty: '中等',
          options: [
            'A. 踌躇(chóu chú) 蹒跚(pán shān) 踯躅(zhí zhú)',
            'B. 踌躇(chóu chú) 蹒跚(pán shān) 踯躅(zhí zhú)',
            'C. 踌躇(chóu chú) 蹒跚(pán shān) 踯躅(zhí zhú)',
            'D. 踌躇(chóu chú) 蹒跚(pán shān) 踯躅(zhí zhú)'
          ],
          answer: 'A',
          analysis: '本题考查多音字的读音。A项中"踌躇"的"躇"读chú，"蹒跚"的"蹒"读pán，"踯躅"的"躅"读zhú。',
          score: 2,
          createTime: new Date(),
          updateTime: new Date(),
          status: 'normal'
        },
        {
          title: '下列句子中，没有语病的一项是',
          type: '单选题',
          subject: '语文',
          difficulty: '中等',
          options: [
            'A. 通过这次活动，使我认识到学习的重要性。',
            'B. 我们要发扬和继承中华民族的优良传统。',
            'C. 他不但学习好，而且品德也很好。',
            'D. 由于天气原因，所以运动会延期举行。'
          ],
          answer: 'C',
          analysis: 'A项缺少主语，B项语序不当，D项关联词使用不当。',
          score: 2,
          createTime: new Date(),
          updateTime: new Date(),
          status: 'normal'
        },
        {
          title: '计算：2x² + 3x - 5 = 0的解是',
          type: '单选题',
          subject: '数学',
          difficulty: '中等',
          options: [
            'A. x = 1, x = -2.5',
            'B. x = -1, x = 2.5',
            'C. x = 1, x = 2.5',
            'D. x = -1, x = -2.5'
          ],
          answer: 'A',
          analysis: '使用求根公式：x = [-b ± √(b²-4ac)]/(2a)，其中a=2，b=3，c=-5。',
          score: 3,
          createTime: new Date(),
          updateTime: new Date(),
          status: 'normal'
        },
        {
          title: '已知函数f(x) = x² - 4x + 3，求f(x)的最小值',
          type: '单选题',
          subject: '数学',
          difficulty: '中等',
          options: [
            'A. -1',
            'B. 0',
            'C. 1',
            'D. 2'
          ],
          answer: 'A',
          analysis: '使用配方法：f(x) = (x-2)² - 1，当x=2时取得最小值-1。',
          score: 3,
          createTime: new Date(),
          updateTime: new Date(),
          status: 'normal'
        }
      ];
      
      this.addLog(`准备添加${questions.length}个试题...`);
      
      // 逐个添加试题，而不是批量添加
      for (let i = 0; i < questions.length; i++) {
        const question = questions[i];
        try {
          const res = await db.collection('questions').add({
            data: question
          });
          this.addLog(`添加试题${i+1}成功，ID: ${res._id}`);
        } catch (e) {
          this.addLog(`添加试题${i+1}失败: ${e.message}`);
          throw e;
        }
      }
      
      this.addLog('所有试题添加完成');
      this.setData({ initQuestionsDone: true });
      
      wx.hideLoading();
      wx.showToast({
        title: '初始化试题成功',
        icon: 'success'
      });
    } catch (error) {
      this.addLog(`初始化试题失败: ${error.message}`);
      wx.hideLoading();
      wx.showToast({
        title: '初始化试题失败',
        icon: 'none'
      });
    }
  },

  // 初始化试卷数据
  async initPapers() {
    wx.showLoading({
      title: '初始化中...',
      mask: true
    });
    
    try {
      const db = wx.cloud.database();
      
      this.addLog('开始初始化试卷数据...');
      
      // 示例试卷数据
      const papers = [
        {
          title: '语文期中测试',
          subject: '语文',
          description: '覆盖语文期中考试重点内容',
          totalScore: 100,
          questionCount: 50,
          duration: 120, // 分钟
          status: '未发布',
          createTime: new Date(),
          updateTime: new Date()
        },
        {
          title: '数学期末测试',
          subject: '数学',
          description: '覆盖数学期末考试重点内容',
          totalScore: 100,
          questionCount: 40,
          duration: 120, // 分钟
          status: '已发布',
          createTime: new Date(),
          updateTime: new Date()
        }
      ];
      
      this.addLog(`准备添加${papers.length}份试卷...`);
      
      // 逐个添加试卷
      for (let i = 0; i < papers.length; i++) {
        const paper = papers[i];
        try {
          const res = await db.collection('papers').add({
            data: paper
          });
          this.addLog(`添加试卷${i+1}成功，ID: ${res._id}`);
        } catch (e) {
          this.addLog(`添加试卷${i+1}失败: ${e.message}`);
          throw e;
        }
      }
      
      this.addLog('所有试卷添加完成');
      this.setData({ initPapersDone: true });
      
      wx.hideLoading();
      wx.showToast({
        title: '初始化试卷成功',
        icon: 'success'
      });
    } catch (error) {
      this.addLog(`初始化试卷失败: ${error.message}`);
      wx.hideLoading();
      wx.showToast({
        title: '初始化试卷失败',
        icon: 'none'
      });
    }
  },

  // 返回上一页
  back() {
    wx.navigateBack();
  }
}); 